<?php

namespace backend\logic;
use think\Db;
use external\SFTools;

class WechatUserLogic {
    /**
     * 获取微信用户信息
     * @return  array          数组对象数据
     */
    public function getWechatUserFindToTicket() {
        $userFind = array();
        $cookie_key = SFTools::getCookieKey();
        $config = config('wechat_config_xhb');
        //通过网站静默授权获取用户信息
        $wechatOauth = new \external\WechatOauth($config['appid'], $config['appsecret']);
        $wechatUserFind = $wechatOauth->getUserInfo();
        $openid = $wechatUserFind['openid'];
        if($wechatUserFind['subscribe'] == 0){
            $wechatAPI = new \external\WechatAPI($config['appid'], $config['appsecret']);
            $wechatUserFind = $wechatAPI->getUserInfo($openid);
        }
        $cache_key_str = $config['appid'] . $openid;
        $cache_key = md5($cache_key_str);
        setcookie($cookie_key, $cache_key, 0, '/');
        $userFind = $openid;
        $userFind['openid'] = $openid;
        if(!empty($wechatUserFind['unionid'])){
            $userFind['unionid'] = $wechatUserFind['unionid'];
        }
        $result = $this->saveWechatUser($wechatUserFind);
        $userFind['user_uuid'] = $result['user_uuid'];
        return $userFind;
    }

    /*public function getUserFindToTicket($data) {
        $wechatUserFind = $this->saveWechatUser($data);
    }*/

    public function saveWechatUser($data) {
        $config = config('wechat_config_xhb');
        $wechatUser =  new \backend\model\WechatUser;
        $wechatUserFind = $wechatUser::where('openid', $data['openid'])->where('token', $data['token'])->find();
        if(empty($wechatUserFind) || !empty('nickname')){
            $wechatUser->save($data);
            $wechatUserFind['openid'] =  $wechatUser->openid;
            $wechatUserFind['user_uuid'] =  $wechatUser->user_uuid;
        }
        return $wechatUserFind;
    }
}